<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <title>系统管理子系統</title>
    <meta name="keywords" content="Bootstrap模版,Bootstrap模版下载,Bootstrap教程,Bootstrap中文"/>
    <meta name="description" content="站长素材提供Bootstrap模版,Bootstrap教程,Bootstrap中文翻译等相关Bootstrap插件下载"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

    <!-- basic styles -->

    <link href="/static/css/bootstrap.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="/static/css/bootstrapValidator.min.css"/>
    <link rel="stylesheet" href="/static/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="/static/css/ace.min.css"/>
    <link rel="stylesheet" href="/static/css/ace-rtl.min.css"/>
    <link rel="stylesheet" href="/static/css/ace-skins.min.css"/>
    <link rel="stylesheet" href="/static/js/select2/select2.css"/>

    <script src="/static/js/jquery-3.4.1.min.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    <script src="/static/js/typeahead-bs2.min.js"></script>
    <script src="/static/js/jquery.form.min.js"></script>
    <script src="/static/js/jquery.dataTables.min.js"></script>
    <script src="/static/js/dataTables.bootstrap.min.js"></script>
    <script src="/static/js/jquery.dataTables.bootstrap.js"></script>
    <script src="/static/js/bootstrapValidator.min.js"></script>
    <script src="/static/js/language/zh_CN.js"></script>
    <script src="/static/js/dataTablesi-i18n-zh_cn.js"></script>
    <script src="/static/js/select2/select2.min.js"></script>

    <script type="text/javascript">
        $(function () {
            //渲染表格
            let mytable = $('#mytab').DataTable({
                "processing": true,
                "serverSide": true,
                "ajax": {
                    url: '/user/query',
                    //查询条件
                    data: {
                        "uno": "",
                        "username": "",
                        "role": ""
                    }
                },
                "language": i18n_cn,//汉化
                "lengthMenu": [3, 5, 10],//每页多少条
                "sDom": '<"top">rt<"bottom"lp><"clear">',//表格控件布局
                //[]左右空格防止跟tm表达式冲突
                "order": [1, 'asc'],
                "columnDefs": [
                    {
                        targets: [0],
                        data: null,
                        orderable: false,
                        render: function (data, type, row, meta) {
                            return '<input type="checkbox" name="id" value="' + row.id + '">';
                        }
                    },
                    {
                        targets: [1],
                        data: 'uno',
                        orderable: true
                    },
                    {
                        targets: [2],
                        data: 'username',
                        orderable: true
                    },
                    {
                        targets: [3],
                        data: 'password',
                        orderable: false,
                    },
                    {
                        targets: [4],
                        data: 'role',
                        orderable: false,
                        render: function (data, type, row, meta) {

                            if (data == 0)
                                return '普通用户';
                            else if (data == 1)
                                return '订票管理员';
                            else if (data == 2)
                                return '系统管理员';
                            else return '';
                        }
                    },
                    {
                        targets: [5],
                        data: 'phone',
                        orderable: false
                    },
                    {
                        className: 'modRole',//必须加一个样式
                        targets: [6],
                        data: null,
                        orderable: false,
                        render: function (data, type, row, meta) {
                            return '<a href="#">修改权限</a>';
                        }
                    }
                ],
            });

            //修改权限超链接绑定单击事件
            $('#mytab tbody').on('click', 'td.modRole', function () {
                //获取【修改权限】按钮所在的行
                let tr = $(this).closest('tr');
                let row = mytable.row(tr);
                let id = row.data().id;

                var thisId = "modTab" + id;
                var modRoleTab = '<form>' +
                    '    权限角色:<select id="' + thisId + '" name="role">' +
                    '    <option value="0">普通用户</option>' +
                    '    <option value="1">订票管理员</option>' +
                    '    <option value="2">系统管理员</option>' +
                    '</select>' +
                    '    <button class="btn btn-xs btn-primary modRoleBtn" type="button">' +
                    '        <i class="icon-pencil bigger-120">提交修改</i>' +
                    '    </button>' +
                    '</form>';

                if (row.child.isShown()) {
                    //隐藏
                    row.child.hide();
                    tr.removeClass('shown');
                } else {
                    //展开
                    row.child(modRoleTab).show();
                    //回显权限角色role下拉列表
                    let thisSelect = document.getElementById(thisId);
                    $(thisSelect).children().each(function () {
                        let roleObj = row.data().role;
                        if (roleObj == $(this).val()) {
                            $(this).prop("selected", "selected");
                        }
                    });
                    //绑定修改权限提交按钮的单击事件
                    $(".modRoleBtn").click(function () {
                        $.ajax({
                            url: "/user/modrole/" + id + "/" + $(thisSelect).val(),
                            type: 'patch',
                            contentType: "application/json;charset=utf-8",
                            dataType: 'json',
                            cache: false,
                            async: false,//同步的方式
                            statusCode: statusCode,
                            success: function (jsonResult) {
                                alert(jsonResult.msg);
                                //隐藏
                                row.child.hide();
                                tr.removeClass('shown');
                                mytable.ajax.reload();
                            }
                        })
                    })
                    tr.addClass('shown');
                }
            });


            //点击新增按钮
            $("#addBtn").click(function () {
                $("#myModalLabel").html("新增");
                $("#username").prop("readonly", null);
                //弹出表单模态窗口
                $('#myModal').modal('show');
            })

            //点击修改按钮
            $("#modBtn").click(function () {
                // alert("请把该功能写完")
                //判断有没有选中一个用户
                var $checked = $("#mytab :checkbox[name=id]:checked");
                if ($checked.length != 1) {
                    alert("必须且最多选择一个用户");
                    return;
                }
                //获取被选中的复选框s所在的行
                let tr = $checked.closest('tr');
                let row = mytable.row(tr);
                //当前行的数据对象
                let u = row.data();
                //表单赋值
                $("#id").val(u.id);
                $("#uno").val(u.uno);
                $("#username").val(u.username);
                $("#username").prop("readonly", "readonly");
                $("#password").val(u.password);
                //回显权限角色role下拉列表
                $("#role option").each(function () {
                    let roleObj = u.role;
                    if (roleObj == $(this).val()) {
                        $(this).prop("selected", "selected");
                    }
                });
                $("#phone").val(u.phone);

                $("#myModalLabel").html("修改");
                //弹出表单模态窗口
                $('#myModal').modal('show');
            })

            //复选框全选
            $("#checkall").click(function () {
                $("#mytab tbody :checkbox").prop("checked", $(this).prop("checked"));
            })

            //点击删除按钮
            $("#delBtn").click(function () {
                //判断有没有选中一个用户
                let $checked = $("#mytab :checkbox[name=id]:checked");
                if ($checked.length < 1) {
                    alert("必须至少选择一个用户");
                    return;
                }
                let ids = $checked.map(function (index, item) {
                    return $(item).val();
                }).get();
                let names = $checked.map(function (index,item){
                    return $(item).parent().next("td").next("td").text();
                }).get();
                // console.log(ids);
                if (confirm("确定要删除[" + names + "]吗?")) {
                    $.ajax({
                        url: "/user/delsome",
                        type: "DELETE",
                        data: JSON.stringify(ids),
                        contentType: "application/json",
                        dataType: 'json',
                        cache: false,
                        async: true,
                        statusCode: statusCode,
                        success: function (jsonResult) {
                            if ("0" == jsonResult.code) {
                                alert(jsonResult.msg);
                                mytable.ajax.reload();
                            }
                        }

                    })
                }
            })
            //点击查询按钮
            $("#queryBtn").click(function () {
                var uno = $("#unoconn").val();
                var username = $("#usernameconn").val();
                var role = $("#roleconn option:selected").val();
                if (mytable) {
                    var param = {
                        "uno": uno,
                        "username": username,
                        "role": role
                    };
                    // console.log(param)
                    //封装参数
                    mytable.settings()[0].ajax.data = param;
                    //重新加载表格
                    mytable.ajax.reload();
                }
            });

            let statusCode = {
                500: function (response) {
                    alert("系统内部异常，请稍后再试")
                },
                400: function (response) {
                    alert("表单参数不合法!")
                    $("#formerrorinfo").html(response.responseJSON.msg)
                },
                403: function (response) {
                    alert("您无权操作该资源!")
                }
            }


            //点击表单的提交按钮
            $('#submitBtn').click(function () {
                //提交的JSON格式数据
                let formParamJson = {
                    "id": $("#id").val(),
                    "uno": $('#uno').val(),
                    "username": $('#username').val(),
                    "password": $('#password').val(),
                    "role": $("#role option:selected").val(),
                    "phone": $("#phone").val()
                }

                // console.log('formParamJson='+JSON.stringify(formParamJson));
                function restfulSubmit(url, requestMethod) {
                    //提交表单 REST风格
                    $.ajax({
                        url: url,
                        type: requestMethod,
                        data: JSON.stringify(formParamJson),
                        contentType: "application/json;charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        async: false,//同步的方式
                        statusCode: statusCode,
                        success: function (jsonResult) {
                            if ("1" == jsonResult.code) {
                                alert(jsonResult.msg);
                                // $('#myModal').modal('hide');
                            } else if ("0" == jsonResult.code) {
                                alert(jsonResult.msg);
                                $('#myModal').modal('hide');
                                //重置form
                                $("#modelForm")[0].reset();
                                // $("#id").select2("val", [""]);
                            }
                        }
                    });
                }

                if ($("#myModalLabel").html() == "新增") {
                    restfulSubmit("/user/add", "POST");
                } else if ($("#myModalLabel").html() == "修改") {
                    restfulSubmit("/user/mod/" + $('#id').val(), "PUT");
                }
            });

            //myModal关闭时重置表单
            $('#myModal').on('hidden.bs.modal', function () {
                $("#modelForm")[0].reset();
                // $("#id").select2("val", [""]);
                //清空表单校验错误提示信息
                $("#formerrorinfo").html("");
                mytable.ajax.reload();
            });
        });
    </script>
</head>
<body>
<div class="breadcrumbs" id="breadcrumbs">
    <script type="text/javascript">
        try {
            ace.settings.check('breadcrumbs', 'fixed')
        } catch (e) {
        }
    </script>
    <ul class="breadcrumb">
        <li>
            <i class="icon-home home-icon"></i>
            <a href="#">后台管理</a>
        </li>
        <li>
            <a href="#">系统管理子系统</a>
        </li>
    </ul>
    <div class="row">
        <div class="col-xs-12">
            <div class="result-title">
                <div>
                    <button id="addBtn" class="btn btn-xs btn-primary" type="button">
                        <i class="icon-plus bigger-120"> 新增</i>
                    </button>
                    <button id="modBtn" class="btn btn-xs btn-warning" type="button">
                        <i class="icon-wrench bigger-120"> 修改</i>
                    </button>
                    <button id="delBtn" class="btn  btn-xs btn-danger" type="button">
                        <i class="icon-trash bigger-120"> 删除</i>
                    </button>
                    编号:<input type="text" id="unoconn">
                    姓名:<input type="text" id="usernameconn">
                    权限角色:<select id="roleconn">
                    <option value="">请选择</option>
                    <option value="0">普通用户</option>
                    <option value="1">订票管理员</option>
                    <option value="2">系统管理员</option>
                </select>
                    <button class="btn btn-xs btn-primary" id="queryBtn" type="button">
                        <i class="icon-search bigger-120"> 查询</i>
                    </button>

                </div>
            </div>
            <div class="table-header">
                用户信息表
            </div>

            <div class="table-responsive">
                <form action="" method="post" id="delForm">
                    <table id="mytab" class="table table-striped table-bordered table-hover">
                        <thead>
                        <tr>
                            <th>
                                <div class="center">
                                    <label>
                                        <input type="checkbox" id="checkall" class="ace"/>
                                        <span class="lbl"></span>
                                    </label>
                                </div>
                            </th>
                            <th>用户编号</th>
                            <th>姓名</th>
                            <th>密码</th>
                            <th>权限角色</th>
                            <th>电话</th>
                            <th>操作</th>
                        </tr>
                        </thead>

                        <tbody>

                        </tbody>
                    </table>
                </form>
            </div>
        </div>
    </div>
</div><!-- /.col -->
<div id="infodiv">
</div>
<div class="modal fade" id="myModal" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                        aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">新增</h4>
            </div>
            <!--该表单使用Ajax方式提交 -->
            <form id="modelForm" class="form-horizontal" method="post">
                <div class="modal-body">

                    <input id="id" type="hidden" name="id" value="">
                    <div class="form-group">
                        <label for="username" class="text-right">用户名: </label>
                        <input id="username" type="text" class="form-control" name="username"
                               placeholder="必填" required>
                    </div>
                    <div class="form-group">
                        <label for="password" class="text-right">密码: </label>
                        <input id="password" type="text" class="form-control" name="password">
                    </div>
                    <div class="form-group">
                        <label for="role" class="text-right">权限角色: </label>
                        <select id="role" name="role">
                            <option value="">请选择</option>
                            <option value="0">普通用户</option>
                            <option value="1">订票管理员</option>
                            <option value="2">系统管理员</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="phone" class="text-right">电话: </label>
                        <input id="phone" type="text" class="form-control" name="phone"
                               placeholder="必填" required>
                    </div>
                    <div id="formerrorinfo" class="form-group" style="color:red">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button id="submitBtn" type="button" class="btn btn-primary">提交</button>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>